package com.baoxin.chenxixc4coach;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.adapter.CourseAdapter;
import com.baoxin.chenxixc4coach.adapter.DateAdapter;
import com.baoxin.chenxixc4coach.bean.Course;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.DialogUtil;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SubjectAdvanceActivity extends BaseActivity implements DateAdapter.DateSelectedLisener,
        DialogInterface.OnClickListener, AdapterView.OnItemClickListener {

    private RecyclerView recyclerView;
    private DateAdapter dateAdapter;
    private GridView gridView;

    private CourseAdapter courseAdapter;
    private List<Course> courseList;

    private Course courseClicked;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subject_advance);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        courseList = (ArrayList) msg.obj;
                        break;
                }
                courseAdapter.setCourseList(courseList);
                courseAdapter.notifyDataSetChanged();
            }
        };

        gridView = findViewById(R.id.gridview_course);
        gridView.setOnItemClickListener(this);
        courseAdapter = new CourseAdapter();
        gridView.setAdapter(courseAdapter);

        recyclerView = findViewById(R.id.recyclerview_date);
        dateAdapter = new DateAdapter(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(dateAdapter);

    }


    //选中日期后更新课程信息
    @Override
    public void updateCourse(String riqi) {
        try {
            JSONObject body = new JSONObject();
            body.put("ofaAtime", riqi);
            NetUtil.post(this, Interfaces.URL_GET_COURSE, body.toString(), new MyCallback(Interfaces.URL_GET_COURSE, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DialogInterface.BUTTON_NEGATIVE:
                break;
            case DialogInterface.BUTTON_POSITIVE:
                releaseCourse(courseClicked.getOfadId());
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        courseClicked = courseList.get(position);
        if (courseClicked.getOfadState() == 0) {
            DialogUtil.showTwoButtonDialog(this, "发布课程",
                    "确定发布" + courseClicked.getPeriod() + "的课程？", this);
        } else {
            CourseDetailActivity.startAction(this, courseClicked);

        }


    }

    /**
     * 课程设置
     *
     * @param view
     */
    public void onCourseSetting(View view) {
        Intent intent = new Intent(this, CourseSettingActivity.class);
        startActivityForResult(intent, 1);
    }

    /**
     * 订单详情
     *
     * @param view
     */
    public void onCourseDetail(View view) {
        Intent intent = new Intent(this, OrderDetailActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {//设置课程后返回
            dateAdapter.initDate();
            dateAdapter.notifyDataSetChanged();
        }
    }

    String tip = "";

    /**
     * 发布未发布的课程
     */
    private void releaseCourse(String ofadId) {
        JSONObject body = new JSONObject();
        try {
            body.put("ofadId", ofadId);
            NetUtil.post(this, Interfaces.URL_RELEASE_COURSE, body.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();

                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");

                        if (code.equals("0")) {
                            tip = "发布成功！";
                        } else {
                            tip = "发布失败！";
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
                                dateAdapter.initDate();
                                dateAdapter.notifyDataSetChanged();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
